package com.atguigu.gmall.seckill.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.SeckillOrder;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.mq.config.RabbitService;
import com.atguigu.gmall.seckill.mapper.SeckillGoodsMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 秒杀下单的监听类
 */
@Component
public class SeckillOrderAddConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 监听排队消息进行秒杀下单
     * @param msg
     */
    @RabbitListener(queues = "seckill_queue")
    public void addOrder(String msg) {
        //将消息的类型转换为排队信息
        UserRecode userRecode = JSONObject.parseObject(msg, UserRecode.class);
        String username = userRecode.getUsername();

//        //进行校验，判断用户是否有未支付的订单
//        Object o = redisTemplate.boundHashOps("SeckillOrder").get(username);
//        if (o != null) {
//            //用户有未支付的秒杀订单
//            //修改排队的状态
//            userRecode.setStatus(3);
//            //更新用户的排队状态
//            redisTemplate.boundValueOps("SeckillStatus_" + username).set(userRecode);
//            return;
//        }

        String time = userRecode.getTime();
        String goodsId = userRecode.getGoodsId();
        //校验商品
        SeckillGoods seckillGoods = (SeckillGoods)redisTemplate.boundHashOps("SeckillGoods_" + time).get(goodsId);
        if (seckillGoods != null) {
            //获取商品库存
//            Integer stockCount = seckillGoods.getStockCount();
            Object o = redisTemplate.boundListOps("seckillGoodsQueue_" + goodsId).rightPop();
            //判断库存
            if (o != null) {
                //构建订单信息
                SeckillOrder seckillOrder = new SeckillOrder();
                seckillOrder.setId(UUID.randomUUID().toString().replace("-", ""));
                seckillOrder.setGoodsId(goodsId);
                seckillOrder.setNum(userRecode.getNum());
                seckillOrder.setMoney(userRecode.getNum() * seckillGoods.getCostPrice().doubleValue() + "");
                seckillOrder.setUserId(username);
                seckillOrder.setCreateTime(userRecode.getCreateTime());
                seckillOrder.setStatus("0");
                //将订单信息存入redis
                redisTemplate.boundHashOps("SeckillOrder_" + username).put(seckillOrder.getId(), seckillOrder);
                //更新库存，同时解决超卖问题
//                int i = seckillGoods.getStockCount() - userRecode.getNum();
                Long stockNum = redisTemplate.boundHashOps("SeckillGoodsStockNum").increment(goodsId, -1);
                seckillGoods.setStockCount(stockNum.intValue());
                if (stockNum > 0) {
                    //数据正常，更新库存
                    redisTemplate.boundHashOps("SeckillGoods_" + time).put(goodsId, seckillGoods);
                }else {
                    //售罄处理，将redis中商品的数据清除掉
                    redisTemplate.boundHashOps("SeckillGoods_" + time).delete(goodsId);
                    //将商品的数据同步到数据库中去
                    seckillGoodsMapper.updateById(seckillGoods);
                }
                //秒杀等待支付，更新排队状态
                userRecode.setStatus(2);
                userRecode.setMoney(Float.valueOf(seckillOrder.getMoney()));
                userRecode.setOrderId(seckillOrder.getId());
                //排队状态更新到redis中
                redisTemplate.boundValueOps("SeckillStatus_" + username).set(userRecode);
                //发送一个延迟消息，记录订单的有效期倒计时
                rabbitService.sendMessage("seckill_dead_exchange",
                        "seckill.dead.order",
                        JSONObject.toJSONString(seckillOrder),
                        "300");//延迟5分钟
                //结束
                return;
            }
        }
        //商品售罄了，下单失败
        //修改排队的状态
        userRecode.setStatus(3);
        //更新用户的排队状态
        redisTemplate.boundValueOps("SeckillStatus_" + username).set(userRecode);
        //删除重复排队标识
        redisTemplate.delete("SeckillUserQueue_" + username);
        return;
    }
}
